<?php

namespace App\Model\PssModel;

use App\Model\BaseModel\BasePssModel;
class TemplateDelivery extends BasePssModel
{
    public $table = 'template_delivery';
    /**
     * 
     * @param array $tpl_ids
     */
    public function getGoodsTemplateByIds( array $tpl_ids = [] )
    {
        $tpl_ids = array_unique($tpl_ids);
        $tpl_ids = array_filter($tpl_ids);
        if( empty($tpl_ids) ) {
            return [];
        }
        $list = $this->whereIn('id',$tpl_ids)->get()->toArray();
        if( empty($list) ) {
            return [];
        }
        $list_map = [];
        foreach ($list as $item ) {
            $list_map[$item['template_id']][] = $item;
            unset($item);
        }
        return $list_map;
    }
    
    /**
     * 获取默认运费模板信息
     */
    public function getDefaultTemplateInfo()
    {
        $defaultTemplateInfo = $this
        ->from($this->table." as td")
        ->select([
            'tda.template_id',
            'tda.init_weight',
            'tda.init_money',
            'tda.increase_weight',
            'tda.increase_money',
        ])
        ->join('template_delivery_area as tda','tda.template_id','=','td.id')
        ->where('tda.is_all_country',1)
        ->first();
        
        $defaultTemplateInfo = $defaultTemplateInfo ? $defaultTemplateInfo->toArray() : [];
        return $defaultTemplateInfo ? $defaultTemplateInfo : [
            'template_id'       => 1,
            'init_weight'       => 0,
            'init_money'        => 0,
            'increase_weight'   => 0,
            'increase_money'    => 0
        ];
    }
    
    /**
     * 根据商品挂载的运费模板ID批量获取全国统一的运费模板信息
     */
    public function getMultiGoodsTemplateListsByTemplateIds( array $template_ids = [] )
    {
        $goodsFreightTemplateLists = $this
        ->from($this->table." as td")
        ->select([
            'tda.template_id',
            'tda.init_weight',
            'tda.init_money',
            'tda.increase_weight',
            'tda.increase_money',
        ])
        ->join('template_delivery_area as tda','tda.template_id','=','td.id')
        ->where('tda.is_all_country',1)
        ->whereIn('td.id',$template_ids)
        ->get()
        ->toArray();
        return array_column($goodsFreightTemplateLists,null,'template_id');
    }
}